package xcmg.device.service.warehouse;

import com.github.pagehelper.PageInfo;
import xcmg.device.infra.exception.CommonBusiExceptions;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.agent.AgentAllotDO;
import xcmg.device.dao.entity.agent.AgentAllotDetailDO;
import xcmg.device.dao.entity.agentReturn.AgentReturnDO;
import xcmg.device.dao.entity.agentReturn.AgentReturnDetailDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.entity.logistics.SendBillDO;
import xcmg.device.dao.entity.sale.SaleReverseDO;
import xcmg.device.dao.entity.sale.SaleReverseDetailDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeReverseDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeReverseDetailDO;
import xcmg.device.dao.entity.warehouse.DeliveryInstructionDO;
import xcmg.device.dao.entity.warehouse.DeliveryInstructionDetailDO;
import xcmg.device.dao.entity.warehouse.WarehouseDeliveryDO;
import xcmg.device.dao.entity.warehouse.WarehouseInboundDO;
import xcmg.device.dao.entity.warehouse.WarehouseInboundDetailDO;
import xcmg.device.dao.entity.warehouse.export.WarehouseInboundExportDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.logistics.SendBillMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInboundDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInboundMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.basic.MaterialsService;
import xcmg.device.service.vo.buyBack.BackInboundAddVO;
import xcmg.device.service.vo.buyBack.BackInboundDetailVO;
import xcmg.device.service.vo.buyBack.BackInboundVO;
import xcmg.device.service.vo.delivery.ReceiptInAddVO;
import xcmg.device.service.vo.delivery.ReceiptInDetailVO;
import xcmg.device.service.vo.delivery.ReceiptInVO;
import xcmg.device.service.vo.logistics.SendBillAddVO;
import xcmg.device.service.vo.logistics.SendBillDetailVO;
import xcmg.device.service.vo.logistics.SendBillVO;
import xcmg.device.service.vo.purchase.PurchaseInboundAddVO;
import xcmg.device.service.vo.purchase.PurchaseInboundDetailVO;
import xcmg.device.service.vo.purchase.PurchaseInboundVO;
import xcmg.device.service.vo.warehouse.AbnormalInAddVO;
import xcmg.device.service.vo.warehouse.AbnormalInDetailVO;
import xcmg.device.service.vo.warehouse.AbnormalInVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundAddVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundDetailVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundVO;
import xcmg.device.service.vo.warehouse.allot.RegionAllotAddVO;
import xcmg.device.service.vo.warehouse.allot.RegionAllotDetailVO;
import xcmg.device.service.vo.warehouse.allot.RegionAllotVO;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WarehouseInboundService {

    @Autowired
    private WarehouseInboundMapper warehouseInboundMapper;

    @Autowired
    private WarehouseInboundDetailMapper warehouseInboundDetailMapper;

    @Autowired
    private WarehouseInboundDetailService warehouseInboundDetailService;

    @Autowired
    private WarehouseInboundRecordService warehouseInboundRecordService;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private CommonService commonService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private PriMaterialsMapper priMaterialsMapper;

    @Autowired
    private MaterialsService materialsService;
    
    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    
    @Autowired
    private WarehouseDeliveryMapper warehouseDeliveryMapper;
    
    @Autowired
    private SendBillMapper sendBillMapper;
    
    @Autowired
    private CompanySupplierMapper companySupplierMapper;
    
    @Autowired
    private CompanyUtil companyUtil;
    
    /**
     * @Author: WangKe
     * @Description: 增加入库记录
     * @Date: 15:40 2018/1/17 0017
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(WarehouseInboundAddVO warehouseInboundAddVO, String userId, String orgId) throws Exception{
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode())
        {
            return ErrorCode.IllegalArument;
        }
        WarehouseInboundVO warehouseInboundVO = warehouseInboundAddVO.getHeaderInfo();
        warehouseInboundVO.setId(textResult.getValue());
        warehouseInboundVO.setInboundOrder(genDocumentService.getDocumentNo(BillDesc.InputNo));
        warehouseInboundVO.setStatus(0);
        warehouseInboundVO.setCreateDate(new Date());
        warehouseInboundVO.setCreaterId(userId);
        warehouseInboundVO.setOrgId(orgId);
        warehouseInboundVO.setCreaterName(commonService.getUserName(userId));

        WarehouseInboundDO warehouseInboundDO = new WarehouseInboundDO();
        BeanUtils.copyProperties(warehouseInboundVO, warehouseInboundDO);

        BigDecimal totalPrice = new BigDecimal(0);
        boolean success;

        //新增入库详情记录
        List<WarehouseInboundDetailVO> detailVOList = warehouseInboundAddVO.getDetailList();
        PriMaterialsDO priMaterialsDO;
        BigDecimal price;
        if(CollectionUtils.isNotEmpty(detailVOList)){
            for(WarehouseInboundDetailVO detail : detailVOList){
                detail.setInboundOrder(warehouseInboundVO.getInboundOrder());
                detail.setOrgId(orgId);
                detail.setCreaterId(userId);
                detail.setCreaterName(warehouseInboundVO.getCreaterName());

                priMaterialsDO = priMaterialsMapper.itemByNo(detail.getMaterialNo(), orgId);
                if(priMaterialsDO != null){
                    if(detail.getTotalPrice() == null && priMaterialsDO.getPrice() != null){
                        price = priMaterialsDO.getPrice().multiply(detail.getAmount())
                                .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                        detail.setTotalPrice(price);
                    }
                    if(StringUtil.isNullOrEmpty(detail.getMaterialType())){
                        detail.setMaterialType(priMaterialsDO.getMaterialsType());
                    }
                }

                if(detail.getTotalPrice() != null){
                    totalPrice = totalPrice.add(detail.getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                success = warehouseInboundDetailService.add(detail).getCode()==0;
                if(!success){ //新增入库详情记录失败
                    throw new Exception("新增入库详情记录失败");
                }
            }
        }

        warehouseInboundDO.setTotalPrice(totalPrice);
        success = warehouseInboundMapper.insert(warehouseInboundDO)>0;
        return success? ErrorCode.Success: ErrorCode.Failure;
    }

    /**
     * @Author: WangKe
     * @Description: 根据主键删除入库记录
     * @Date: 15:40 2018/1/17 0017
     */
    public ErrorCode delete(List<String> ids, String orgId){
        List<String> orderList = warehouseInboundMapper.findOrderList(ids);
        if(ListUtil.isNullOrEmpty(orderList)){
            return ErrorCode.IllegalArument;
        }
        boolean success = warehouseInboundMapper.remove(ids)>0;
        //删除入库详情记录
        if(success){
            warehouseInboundDetailService.deleteByInboundOrderList(orderList, orgId);
            warehouseInboundRecordService.deleteByInboundOrderList(orderList, orgId);
        }
        return success? ErrorCode.Success: ErrorCode.WarehouseIdError;
    }

    /**
     * @Author: WangKe
     * @Description: 根据业务单号删除事务单
     * @Date: 2018/3/8 0008
     */
    public ErrorCode removeByBusinessOrders(List<String> businessOrders, String orgId){
        if(ListUtil.isNullOrEmpty(businessOrders)){
            return ErrorCode.IllegalArument;
        }
        return this.delete(warehouseInboundMapper.findIdsByBusinessOrders(businessOrders, orgId), orgId);
    }

    /**
     * @Author: WangKe
     * @Description: 查找入库记录列表
     * @Date: 15:44 2018/1/17 0017
     */
    public PageCommonVO list(SearchCommonVO<WarehouseInboundVO> condition) {
        PageCommonVO<WarehouseInboundVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<WarehouseInboundDO> doList = warehouseInboundMapper.list(condition.getFilters());
        List<WarehouseInboundVO> voList = new ArrayList<WarehouseInboundVO>();
        for (WarehouseInboundDO entity : doList) {
            WarehouseInboundVO model = new WarehouseInboundVO();
            BeanUtils.copyProperties(entity, model);
            voList.add(model);
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public List<WarehouseInboundDO> list(WarehouseInboundVO vo){
        return warehouseInboundMapper.list(vo);
    }

    /**
     * @Author: WangKe
     * @Description: 根据主键查找实体
     * @Date: 2018/1/19 0019
     */
    public WarehouseInboundAddVO findByPK(String id, String type, String orgId){
        WarehouseInboundAddVO model = new WarehouseInboundAddVO();
        WarehouseInboundDO entity;
        if("id".equals(type)){
            entity = warehouseInboundMapper.selectByPrimaryKey(id);
        }else{
            entity = warehouseInboundMapper.selectByOrder(id, orgId);
            if(entity != null) {
                orgId = entity.getOrgId();
            }
        }
        if(entity == null){
            return null;
        }
        WarehouseInboundDetailVO vo = new WarehouseInboundDetailVO();
        vo.setInboundOrder(entity.getInboundOrder());
        List<WarehouseInboundDetailDO> doList = warehouseInboundDetailService.findByInboundOrder(entity.getInboundOrder(), orgId);

        List<WarehouseInboundDetailVO> voList = new ArrayList<WarehouseInboundDetailVO>();
        if(CollectionUtils.isNotEmpty(doList)){
            WarehouseInboundDetailVO warehouseInboundDetailVO = null;
            for(WarehouseInboundDetailDO m:doList){
                warehouseInboundDetailVO = new WarehouseInboundDetailVO();
                BeanUtils.copyProperties(m, warehouseInboundDetailVO);
                voList.add(warehouseInboundDetailVO);
            }
        }
        WarehouseInboundVO warehouseInboundVO = new WarehouseInboundVO();
        BeanUtils.copyProperties(entity, warehouseInboundVO);
        convertSupplierCode(warehouseInboundVO);

        model.setHeaderInfo(warehouseInboundVO);
        model.setDetailList(voList);

        return model;
    }

    private void convertSupplierCode(WarehouseInboundVO warehouseInboundVO) {
        if (BillDesc.SendBill.getDesc().equals(warehouseInboundVO.getBusinessSingle())) {
            SendBillDO sendBillDO = sendBillMapper.itemByBillNo(warehouseInboundVO.getBusinessOrder());
            if (sendBillDO != null) {
                CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), sendBillDO.getSoldOrgId());
                if (companySupplierDO != null) {
                    warehouseInboundVO.setSupplierCode(companySupplierDO.getSupplierCode());
                }
            }
        }
    }

    public List<WarehouseInboundDetailVO> insitructionDetail(WarehouseInboundDetailVO warehouseInboundDetailVO) {
        List<WarehouseInboundDetailDO> doList = warehouseInboundDetailMapper.list(warehouseInboundDetailVO);
        List<WarehouseInboundDetailVO> voList = new ArrayList<WarehouseInboundDetailVO>();
        if (CollectionUtils.isNotEmpty(doList)) {
            WarehouseInboundDetailVO voEntity = null;
            for (WarehouseInboundDetailDO m : doList) {
                voEntity = new WarehouseInboundDetailVO();
                BeanUtils.copyProperties(m, voEntity);
                voList.add(voEntity);
            }
        }
        return voList;
    }

    public boolean updateByPK(WarehouseInboundDO model){
        return warehouseInboundMapper.updateByPrimaryKeySelective(model)>0;
    }

    /**
     * @Author: WangKe
     * @Description: 在新增非正常入库单时新增入库单
     * @Date: 2018/2/2 0002
     */
    public boolean saveByAbnormalIn(AbnormalInAddVO abnormalInAddVO, String userId, String orgId, String supplierOrgId)throws Exception{
        if(abnormalInAddVO == null){
            return false;
        }
        AbnormalInVO vo = abnormalInAddVO.getHeaderInfo();
        List<AbnormalInDetailVO> voList = abnormalInAddVO.getDetailList();

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<WarehouseInboundDetailVO>();
        inboundVO.setBusinessSingle(vo.getAbnormalNo().substring(0, 4));
        inboundVO.setBusinessOrder(vo.getAbnormalNo());
        inboundVO.setWarehouseCode(vo.getInLocation());
        inboundVO.setInArea(vo.getInArea());
        inboundVO.setSapInArea(vo.getSapInArea());
        inboundVO.setSplitOrder(vo.getSplitOrder());

        BigDecimal num = BigDecimal.ZERO;
        if(CollectionUtils.isNotEmpty(voList)){
            WarehouseInboundDetailVO detail;
            for(AbnormalInDetailVO a : voList){
                detail = new WarehouseInboundDetailVO();
                detail.setBusinessSingle(vo.getAbnormalNo().substring(0, 4));
                detail.setBusinessOrder(vo.getAbnormalNo());
                detail.setMaterialNo(a.getMaterialsNo());
                detail.setMaterialName(a.getMaterialsDes());
                detail.setMaterialType(a.getMaterialsType());
                detail.setUnit(a.getUnit());
                detail.setAmount(a.getQty());
                detail.setRealAmount(BigDecimal.ZERO);

                num = num.add(a.getQty());
                detailList.add(detail);

                if(!StringUtil.isNullOrEmpty(supplierOrgId)){
                    materialsService.saveByInbound(detail.getMaterialNo(), orgId, supplierOrgId);
                }
            }
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在新增区域调拨单时新增入库单
     * @Date: 2018/2/11 0011
     */
    public boolean saveByRegionAllotIn(RegionAllotAddVO regionAllotAddVO, String userId, String orgId) throws Exception{
        if(regionAllotAddVO == null){
            return false;
        }
        RegionAllotVO allotVO = regionAllotAddVO.getHeaderInfo();
        List<RegionAllotDetailVO> detailVOList = regionAllotAddVO.getDetailList();

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<WarehouseInboundDetailVO>();
        inboundVO.setBusinessSingle(allotVO.getAllotOrder().substring(0, 4));
        inboundVO.setBusinessOrder(allotVO.getAllotOrder());
        inboundVO.setWarehouseCode(allotVO.getInLocation());
        inboundVO.setInArea(allotVO.getInArea());
        inboundVO.setSapInArea(allotVO.getSapInArea());

        if(ListUtil.isNullOrEmpty(detailVOList)){
            return false;
        }
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(RegionAllotDetailVO allotDetailVO : detailVOList){
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(allotDetailVO.getMaterialNo());
            detail.setMaterialName(allotDetailVO.getMaterialName());
            detail.setMaterialType(allotDetailVO.getMaterialType());
            detail.setUnit(allotDetailVO.getUnit());
            detail.setAmount(allotDetailVO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(allotDetailVO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 导出入库数据列表信息
     * @Date: 2018/2/7 0007
     */
    public void export(List<String> ids)throws Exception{
        invokeExport(warehouseInboundMapper.findListForExport(ids));
    }

    /**
     * @Author: WangKe
     * @Description:
     * @Date: 2018/2/7 0007
     */
    public void exportAll(WarehouseInboundVO condition)throws Exception{
        Integer count = warehouseInboundMapper.findCountForExportAll(condition);
        List<WarehouseInboundExportDO> dataList = new ArrayList<>();
        int times = count/500+1;
        for(int i=0; i<times; i++){
            PageHelperPlus.startPage(i + 1, 500, "create_date desc");
            dataList.addAll(warehouseInboundMapper.findListForExportAll(condition));
        }
        invokeExport(dataList);
    }


    /**
     * @Author: WangKe
     * @Description: 导出入库数据列表信息
     * @Date: 2018/2/7 0007
     */
    private void invokeExport(List<WarehouseInboundExportDO> doList)throws Exception{
        if(ListUtil.isNullOrEmpty(doList)){
            return;
        }
        String title = "入库数据导出";
        String[] rowsName = new String[]{"序号","入库单号","业务类别","业务单号","供应商",
                "备注信息","零件编码", "零件名称", "零件类型", "拟入库数量", "实际入库数量", "总价", "单位", "入库状态",
                "打印数量", "打印状态", "制单人", "制单日期"};
        List<Object[]>  dataList = new ArrayList<Object[]>();
        Object[] objs;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < doList.size(); i++) {
            WarehouseInboundExportDO inboundExportDO = doList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i+1;
            objs[1] = inboundExportDO.getInboundOrder();
            objs[2] = inboundExportDO.getBusinessSingle();
            objs[3] = inboundExportDO.getBusinessOrder();
            objs[4] = inboundExportDO.getSupplier();
            objs[5] = inboundExportDO.getNote();
            objs[6] = inboundExportDO.getMaterialNo();
            objs[7] = inboundExportDO.getMaterialName();
            objs[8] = inboundExportDO.getMaterialType();
            objs[9] = inboundExportDO.getAmount();
            objs[10] = inboundExportDO.getRealAmount();
            objs[11] = inboundExportDO.getTotalPrice();
            objs[12] = inboundExportDO.getUnit();
            objs[13] = getState(inboundExportDO.getStatus());
            objs[14] = inboundExportDO.getPrintNum()==null?0:inboundExportDO.getPrintNum();
            objs[15] = getState(inboundExportDO.getPrintState());
            objs[16] = inboundExportDO.getCreaterName();
            objs[17] = sdf.format(inboundExportDO.getCreateDate());
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    private String getState(Integer state){
        if(state == null){
            state = 0;
        }
        if(state == 0){
            return "未完成";
        }else if(state == 1){
            return "部分完成";
        }else{
            return "已完成";
        }
    }

    /**
     * @Author: WangKe
     * @Description: 在代理商调拨单调入审核通过时新增入库单
     * @Date: 2018/2/27 0027
     */
    public boolean saveByAgentAllotIn(AgentAllotDO agentAllotDO, List<AgentAllotDetailDO> detailVOList,
                                      String userId, String orgId) throws Exception{
        if(agentAllotDO == null || ListUtil.isNullOrEmpty(detailVOList)){
            return false;
        }

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<WarehouseInboundDetailVO>();
        inboundVO.setBusinessSingle(agentAllotDO.getAllotOrder().substring(0, 4));
        inboundVO.setBusinessOrder(agentAllotDO.getAllotOrder());
        inboundVO.setInArea(agentAllotDO.getInArea());
        inboundVO.setSapInArea(agentAllotDO.getSapInArea());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(AgentAllotDetailDO allotDetailDO : detailVOList){
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(allotDetailDO.getMaterialNo());
            detail.setMaterialName(allotDetailDO.getMaterialName());
            detail.setMaterialType(allotDetailDO.getMaterialType());
            detail.setUnit(allotDetailDO.getUnit());
            detail.setAmount(allotDetailDO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(allotDetailDO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在生成冲销入库时新增入库事物单
     * @Date: 2018/3/7 0007
     */
    public boolean saveBySaleReverseIn(SaleReverseDO SaleReverseDO, List<SaleReverseDetailDO> detailDOList,
                                       String userId, String orgId) throws Exception{
        if(SaleReverseDO == null || ListUtil.isNullOrEmpty(detailDOList)){
            return false;
        }

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(SaleReverseDO.getReverseOrder().substring(0, 4));
        inboundVO.setBusinessOrder(SaleReverseDO.getReverseOrder());
        inboundVO.setWarehouseCode(SaleReverseDO.getWarehouseCode());
        inboundVO.setInArea(SaleReverseDO.getInArea());
        inboundVO.setSapInArea(SaleReverseDO.getSapInArea());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(SaleReverseDetailDO reverseDetailDO : detailDOList){
            if(reverseDetailDO.getAmount() == null || reverseDetailDO.getAmount().compareTo(BigDecimal.ZERO) == 0){
                continue;
            }
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(reverseDetailDO.getMaterialNo());
            detail.setMaterialName(reverseDetailDO.getMaterialName());
            detail.setMaterialType(reverseDetailDO.getMaterialType());
            detail.setUnit(reverseDetailDO.getUnit());
            detail.setAmount(reverseDetailDO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(reverseDetailDO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在生成三包冲销入库时新增入库事物单
     * @Date: 2018/7/11 00011
     */
    public boolean saveByThreeReverseIn(ThreeReverseDO threeReverseDO, List<ThreeReverseDetailDO> detailDOList,
                                        String userId, String orgId) throws Exception{
        if(threeReverseDO == null || ListUtil.isNullOrEmpty(detailDOList)){
            return false;
        }

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(threeReverseDO.getReverseOrder().substring(0, 4));
        inboundVO.setBusinessOrder(threeReverseDO.getReverseOrder());
        inboundVO.setWarehouseCode(threeReverseDO.getWarehouseCode());
        inboundVO.setInArea(threeReverseDO.getInArea());
        inboundVO.setSapInArea(threeReverseDO.getSapInArea());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(ThreeReverseDetailDO reverseDetailDO : detailDOList){
            if(reverseDetailDO.getAmount() == null || reverseDetailDO.getAmount().compareTo(BigDecimal.ZERO) == 0){
                continue;
            }
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(reverseDetailDO.getMaterialNo());
            detail.setMaterialName(reverseDetailDO.getMaterialName());
            detail.setMaterialType(reverseDetailDO.getMaterialType());
            detail.setUnit(reverseDetailDO.getUnit());
            detail.setAmount(reverseDetailDO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(reverseDetailDO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在新增采购入库单时新增入库事物单
     * @Date: 2018/3/19 0019
     */
    public boolean saveByPurchaseInbound(PurchaseInboundAddVO purchaseInboundAddVO, String userId, String orgId) throws Exception{
        if(purchaseInboundAddVO == null || purchaseInboundAddVO.getHeaderInfo() == null || ListUtil.isNullOrEmpty(purchaseInboundAddVO.getDetailList())){
            return false;
        }
        PurchaseInboundVO purchaseInboundVO = purchaseInboundAddVO.getHeaderInfo();
        List<PurchaseInboundDetailVO> detailVOList = purchaseInboundAddVO.getDetailList();

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(purchaseInboundVO.getPurchaseInboundOrder().substring(0, 4));
        inboundVO.setBusinessOrder(purchaseInboundVO.getPurchaseInboundOrder());
        inboundVO.setWarehouseCode(purchaseInboundVO.getWarehouseCode());
        inboundVO.setSupplier(purchaseInboundVO.getSupplierOrgId());
        inboundVO.setInArea(purchaseInboundVO.getInArea());
        inboundVO.setSapInArea(purchaseInboundVO.getSapInArea());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(PurchaseInboundDetailVO purchaseInboundDetailVO : detailVOList){
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(purchaseInboundDetailVO.getMaterialNo());
            detail.setMaterialName(purchaseInboundDetailVO.getMaterialName());
            detail.setMaterialType(purchaseInboundDetailVO.getMaterialType());
            detail.setUnit(purchaseInboundDetailVO.getUnit());
            detail.setAmount(purchaseInboundDetailVO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);
            detail.setRowNo(purchaseInboundDetailVO.getRowNo());

            num = num.add(purchaseInboundDetailVO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在新增回购入库单时新增入库事物单
     * @Date: 2018/8/9 0009
     */
    public boolean saveByBackInbound(BackInboundAddVO backInboundAddVO, String userId, String orgId) throws Exception{
        if(backInboundAddVO == null || backInboundAddVO.getHeaderInfo() == null || ListUtil.isNullOrEmpty(backInboundAddVO.getMaterialList())){
            return false;
        }
        BackInboundVO backInboundVO = backInboundAddVO.getHeaderInfo();
        List<BackInboundDetailVO> detailVOList = backInboundAddVO.getMaterialList();

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(backInboundVO.getInboundOrder().substring(0, 4));
        inboundVO.setBusinessOrder(backInboundVO.getInboundOrder());
        inboundVO.setWarehouseCode(backInboundVO.getWarehouseCode());
        inboundVO.setInArea(backInboundVO.getInArea());
        inboundVO.setSapInArea(backInboundVO.getSapInArea());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(BackInboundDetailVO backInboundDetailVO : detailVOList){
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(backInboundDetailVO.getMaterialsNo());
            detail.setMaterialName(backInboundDetailVO.getMaterialsDes());
            detail.setMaterialType(backInboundDetailVO.getMaterialsType());
            detail.setUnit(backInboundDetailVO.getUnit());
            detail.setAmount(backInboundDetailVO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(backInboundDetailVO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }
    
    public Integer getInvalidCountByBusinessOrder(String businessOrderNo) {
        return warehouseInboundMapper.getInvalidCountByBusinessOrder(businessOrderNo);
    }
    
    public int updateInboundToValid(SendBillAddVO sendBillAddVO, String userId, String userName, String orgId) {
        String businessOrder = sendBillAddVO.getHeaderInfo().getSendOrder();
        warehouseInboundDetailMapper.updateToCurrentOperator(businessOrder, sendBillAddVO.getHeaderInfo().getSoldOrgId(), userId, userName, orgId);
        return warehouseInboundMapper.updateInboundToValid(businessOrder, userId, orgId, commonService.getUserName(userId));
    }

    /**
     * @Author: WangKe
     * @Description: 在新增送货单时新增入库事物单
     * @Date: 2018/9/29 0029
     */
    public boolean saveBySendBill(SendBillAddVO sendBillAddVO, String userId, String orgId, String applyOrgId, Integer invalidFlag) throws Exception{
        if(sendBillAddVO == null || sendBillAddVO.getHeaderInfo() == null || ListUtil.isNullOrEmpty(sendBillAddVO.getMaterialsList())){
            return false;
        }
        SendBillVO sendBillVO = sendBillAddVO.getHeaderInfo();
        List<SendBillDetailVO> detailVOList = sendBillAddVO.getMaterialsList();

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(sendBillVO.getSendOrder().substring(0, 4));
        inboundVO.setBusinessOrder(sendBillVO.getSendOrder());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(SendBillDetailVO sendBillDetailVO : detailVOList){
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(sendBillDetailVO.getMaterialsNo());
            detail.setMaterialName(sendBillDetailVO.getMaterialsDes());
            detail.setMaterialType(sendBillDetailVO.getMaterialsType());
            detail.setUnit(sendBillDetailVO.getUnit());
            detail.setAmount(sendBillDetailVO.getQty());
            detail.setRealAmount(BigDecimal.ZERO);
            detail.setRowNo(sendBillDetailVO.getRowNo());

            num = num.add(sendBillDetailVO.getQty());
            detailList.add(detail);
            //如果零件不存在新增零件记录
            Integer sendType = sendBillVO.getSendType();
            CompanyInfoDO companyInfoDO = companyInfoMapper.item(sendBillAddVO.getHeaderInfo().getSoldOrgId());
            if(sendType != null && sendType == 0){//非直投，使用供应商零件扩充代理商不存在的零件
                materialsService.saveByInbound(detail.getMaterialNo(), sendBillAddVO.getHeaderInfo().getDeliveryOrgId(), sendBillAddVO.getHeaderInfo().getSoldOrgId());
            }else if(companyInfoDO != null && "1".equals(companyInfoDO.getCompanyType())){
                materialsService.saveByInbound(detail.getMaterialNo(), sendBillAddVO.getHeaderInfo().getDeliveryOrgId(), sendBillAddVO.getHeaderInfo().getSoldOrgId());
            }else{//直投，使用主机厂零件扩充代理商不存在的零件
                materialsService.saveByInbound(detail.getMaterialNo(), sendBillAddVO.getHeaderInfo().getDeliveryOrgId(), sendBillAddVO.getHeaderInfo().getApplyOrgId());
            }
        }
        inboundVO.setAmount(num);
        if(Integer.valueOf(1).equals(invalidFlag)) {
            inboundVO.setInvalidFlag(invalidFlag);
        }else {
            inboundVO.setInvalidFlag(0);
        }
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在新增配送指令入库单时新增入库事物单
     * @Date: 2018/4/17 0017
     */
    public boolean saveByDeliveryInstruction(DeliveryInstructionDO deliveryInstructionDO, List<DeliveryInstructionDetailDO> detailDOList,
                                               String userId, String orgId) throws Exception{
        if(deliveryInstructionDO == null || ListUtil.isNullOrEmpty(detailDOList)){
            return false;
        }
        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(deliveryInstructionDO.getDeliveryOrder().substring(0, 4));
        inboundVO.setBusinessOrder(deliveryInstructionDO.getDeliveryOrder());
        inboundVO.setWarehouseCode(deliveryInstructionDO.getWarehouseCode());
        inboundVO.setInArea(deliveryInstructionDO.getInArea());
        inboundVO.setSapInArea(deliveryInstructionDO.getSapInArea());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(DeliveryInstructionDetailDO reverseDetailDO : detailDOList){
            if(reverseDetailDO.getAmount() == null || reverseDetailDO.getAmount().compareTo(BigDecimal.ZERO) == 0){
                continue;
            }
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(reverseDetailDO.getMaterialNo());
            detail.setMaterialName(reverseDetailDO.getMaterialName());
            detail.setMaterialType(reverseDetailDO.getMaterialType());
            detail.setUnit(reverseDetailDO.getUnit());
            detail.setAmount(reverseDetailDO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);
            detail.setRowNo(reverseDetailDO.getRowNo());
            detail.setDeliveryInstructionNo(reverseDetailDO.getDeliveryInstructionNo());
            num = num.add(reverseDetailDO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 在新增运单入库单时新增入库事物单
     * @Date: 2019/2/1 0001
     */
    public boolean saveByReceiptIn(ReceiptInAddVO receiptInAddVO, String userId, String orgId,String supplierOrgId) throws Exception{
        if(receiptInAddVO == null || receiptInAddVO.getHeaderInfo() == null || ListUtil.isNullOrEmpty(receiptInAddVO.getDetailList())){
            return false;
        }
        ReceiptInVO receiptInVO = receiptInAddVO.getHeaderInfo();
        List<ReceiptInDetailVO> detailVOList = receiptInAddVO.getDetailList();

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(receiptInVO.getBillNo().substring(0, 4));
        inboundVO.setBusinessOrder(receiptInVO.getBillNo());
        inboundVO.setWarehouseCode(receiptInVO.getWarehouseCode());
        inboundVO.setInArea(receiptInVO.getAreaCode());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(ReceiptInDetailVO receiptInDetailVO : detailVOList){
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(receiptInDetailVO.getMaterialsNo());
            detail.setMaterialName(receiptInDetailVO.getMaterialsDes());
            detail.setMaterialType(receiptInDetailVO.getMaterialsType());
            detail.setUnit(receiptInDetailVO.getUnit());
            detail.setAmount(receiptInDetailVO.getAmount());
            detail.setRealAmount(BigDecimal.ZERO);

            if(!StringUtil.isNullOrEmpty(supplierOrgId)){
                materialsService.saveByInbound(detail.getMaterialNo(), orgId, supplierOrgId);
            }
            num = num.add(receiptInDetailVO.getAmount());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }

    /**
     * @Author: WangKe
     * @Description: 根据业务单号和零件编码更新单条入库详情记录
     * @Date: 2018/3/7 0007
     */
    public ErrorCode updateDetailState(String businessOrder, String materialNo, BigDecimal amount, Integer state, String orgId){
        WarehouseInboundDetailVO inboundDetailVO = new WarehouseInboundDetailVO();
        inboundDetailVO.setBusinessOrder(businessOrder);
        inboundDetailVO.setMaterialNo(materialNo);
        inboundDetailVO.setOrgId(orgId);
        List<WarehouseInboundDetailDO> inboundDetailList = warehouseInboundDetailMapper.list(inboundDetailVO);
        if(ListUtil.isNullOrEmpty(inboundDetailList)){
            return ErrorCode.IllegalArument;
        }
        WarehouseInboundDetailDO inboundDetailDO = inboundDetailList.get(0);
        if(null==inboundDetailDO)
        {
            return ErrorCode.IllegalArument;
        }
        //修改后的数量不能小于已经打印的数量
        if(state!=3 && amount.compareTo(inboundDetailDO.getPrintNum()) < 0){
            throw new CommonBusiExceptions("修改后的数量不能小于已经打印的数量");
        }
        if(state!=3){
            inboundDetailDO.setAmount(amount);
        }
        inboundDetailDO.setStatus(state);
        if(state!=3&&inboundDetailDO.getPrintState() > 0){
            if(inboundDetailDO.getPrintNum().compareTo(inboundDetailDO.getAmount()) < 0){
                inboundDetailDO.setPrintState(1);
            }else{
                inboundDetailDO.setPrintState(2);
            }
        }
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialNo, orgId);
        if(state!=3&&priMaterialsDO != null){
            if(priMaterialsDO.getPrice() != null){
                BigDecimal price = priMaterialsDO.getPrice().multiply(amount)
                        .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                inboundDetailDO.setTotalPrice(price);
            }
            if(StringUtil.isNullOrEmpty(inboundDetailDO.getMaterialType())){
                inboundDetailDO.setMaterialType(priMaterialsDO.getMaterialsType());
            }
        }
        return warehouseInboundDetailMapper.updateByPrimaryKeySelective(inboundDetailDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Author: WangKe
     * @Description: 根据业务单号和零件编码更新单条入库详情记录
     * @Date: 2018/3/7 0007
     */
    public ErrorCode updateDetailStateRowNo(String businessOrder, String materialNo, BigDecimal amount, Integer state, Integer rowNo, String orgId){
        WarehouseInboundDetailVO inboundDetailVO = new WarehouseInboundDetailVO();
        inboundDetailVO.setBusinessOrder(businessOrder);
        inboundDetailVO.setMaterialNo(materialNo);
        inboundDetailVO.setOrgId(orgId);
        inboundDetailVO.setRowNo(rowNo);
        List<WarehouseInboundDetailDO> inboundDetailList = warehouseInboundDetailMapper.list(inboundDetailVO);
        if(ListUtil.isNullOrEmpty(inboundDetailList)){
            return ErrorCode.IllegalArument;
        }
        WarehouseInboundDetailDO inboundDetailDO = inboundDetailList.get(0);
        if(null==inboundDetailDO)
        {
            return ErrorCode.IllegalArument;
        }
        //修改后的数量不能小于已经打印的数量
        if(state!=3 && amount.compareTo(inboundDetailDO.getPrintNum()) < 0){
            return ErrorCode.AbnormalInUpdateError;
        }
        if(state!=3){
            inboundDetailDO.setAmount(amount);
        }
        inboundDetailDO.setStatus(state);
        if(state!=3&&inboundDetailDO.getPrintState() > 0){
            if(inboundDetailDO.getPrintNum().compareTo(inboundDetailDO.getAmount()) < 0){
                inboundDetailDO.setPrintState(1);
            }else{
                inboundDetailDO.setPrintState(2);
            }
        }
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialNo, orgId);
        if(state!=3&&priMaterialsDO != null){
            if(priMaterialsDO.getPrice() != null){
                BigDecimal price = priMaterialsDO.getPrice().multiply(amount)
                        .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                inboundDetailDO.setTotalPrice(price);
            }
            if(StringUtil.isNullOrEmpty(inboundDetailDO.getMaterialType())){
                inboundDetailDO.setMaterialType(priMaterialsDO.getMaterialsType());
            }
        }
        return warehouseInboundDetailMapper.updateByPrimaryKeySelective(inboundDetailDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Author: WangKe
     * @Description: 根据业务单号更新入库事物单状态
     * @Date: 2018/3/7 0007
     */
    public ErrorCode updateState(String businessOrder, Integer state, String orgId){
        WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(businessOrder, orgId);
        if(inboundDO == null){
            return ErrorCode.IllegalArument;
        }
        inboundDO.setStatus(state);
        return warehouseInboundMapper.updateByPrimaryKeySelective(inboundDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Author: WangKe
     * @Description: 无条码入库时更新事务单状态
     * @Date: 2018/4/4 0004
     */
    public boolean updateStateNoBarcode(String businessOrder, String materialNo, Integer state, String orgId){
        boolean success = warehouseInboundMapper.updateStateNoBarcode(state, businessOrder, orgId)>0;
        if(!success){
            return false;
        }
        success = warehouseInboundDetailMapper.updateStateNoBarcode(state, businessOrder, materialNo, orgId)>0;
        return success;
    }


    /**
     * 根据零件信息删除入库单详细
     * @param record
     * @return
     */
    public ErrorCode deleteByMaterial(WarehouseInboundDetailDO record)
    {
        warehouseInboundDetailMapper.deleteByMaterial(record);
        return ErrorCode.Success;
    }

    /**
     * 更新入库事务单的入库数量和总价格
     * @param billNo String
     * @param orgId String
     * @return ErrorCode
     */
    public ErrorCode refreshAmountAndPrice(String billNo,String orgId)
    {
        WarehouseInboundDO warehouseInboundDO = warehouseInboundMapper.selectByOrder(billNo,orgId);

        List<WarehouseInboundDetailDO> inboundDetailDOs =    warehouseInboundDetailService.findByInboundOrder(warehouseInboundDO.getInboundOrder(),orgId);

        BigDecimal totalPrice = new BigDecimal(0);
        BigDecimal totalAmount = BigDecimal.ZERO;
        for(WarehouseInboundDetailDO tmp:inboundDetailDOs)
        {
            if(null==tmp)
            {
                continue;
            }
            if(tmp.getTotalPrice() != null){
                totalPrice = totalPrice.add(tmp.getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            totalAmount = totalAmount.add(tmp.getAmount());
        }
        warehouseInboundDO.setTotalPrice(totalPrice);
        warehouseInboundDO.setAmount(totalAmount);
        warehouseInboundMapper.updateByPrimaryKeySelective(warehouseInboundDO);
        return ErrorCode.Success;
    }


    public ErrorCode updateSapOrder(String businessOrder, String sapOrder, String orgId){
        WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(businessOrder, orgId);
        if(inboundDO != null){
            inboundDO.setSapOrder(sapOrder);
            return warehouseInboundMapper.updateByPrimaryKeySelective(inboundDO)>0?ErrorCode.Success:ErrorCode.Failure;
        }

        WarehouseDeliveryDO warehouseDeliveryDO = warehouseDeliveryMapper.findByBusinessOrder(businessOrder, orgId);
        if(warehouseDeliveryDO == null){
            return ErrorCode.IllegalArument;
        }
        warehouseDeliveryDO.setSapOrder(sapOrder);
        return warehouseDeliveryMapper.updateByPrimaryKey(warehouseDeliveryDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Description: 在代理商退货审核通过时新增入库单
     */
    public boolean saveByRefundInbound(AgentReturnDO agentReturnDO, List<AgentReturnDetailDO> detailVOList,
                                      String userId, String orgId) throws Exception{
        if(agentReturnDO == null || ListUtil.isNullOrEmpty(detailVOList)){
            return false;
        }

        WarehouseInboundVO inboundVO = new WarehouseInboundVO();
        List<WarehouseInboundDetailVO> detailList = new ArrayList<>();
        inboundVO.setBusinessSingle(agentReturnDO.getReturnNo().substring(0, 4));
        inboundVO.setBusinessOrder(agentReturnDO.getReturnNo());
        inboundVO.setWarehouseCode(agentReturnDO.getWarehouseCode());
        BigDecimal num = BigDecimal.ZERO;
        WarehouseInboundDetailVO detail;
        for(AgentReturnDetailDO agentReturnDetailDO : detailVOList){
            detail = new WarehouseInboundDetailVO();
            detail.setBusinessSingle(inboundVO.getBusinessSingle());
            detail.setBusinessOrder(inboundVO.getBusinessOrder());
            detail.setMaterialNo(agentReturnDetailDO.getMaterialNo());
            detail.setMaterialName(agentReturnDetailDO.getMaterialDesc());
            detail.setUnit(agentReturnDetailDO.getUnit());
            detail.setAmount(agentReturnDetailDO.getReturnQuantity());
            detail.setRealAmount(BigDecimal.ZERO);

            num = num.add(agentReturnDetailDO.getReturnQuantity());
            detailList.add(detail);
        }
        inboundVO.setAmount(num);
        WarehouseInboundAddVO inboundAddVO = new WarehouseInboundAddVO();
        inboundAddVO.setHeaderInfo(inboundVO);
        inboundAddVO.setDetailList(detailList);

        ErrorCode code = this.add(inboundAddVO, userId, orgId);
        return code.getCode() == 0;
    }
    
    public WarehouseInboundDO getByOrder(String businessOrder,String orgId){
        if(StringUtils.isEmpty(businessOrder) || StringUtils.isEmpty(orgId)){
            return null;
        }
        WarehouseInboundDO warehouseInboundDO = warehouseInboundMapper.selectByOrder(businessOrder, orgId);
        return warehouseInboundDO;
    }
    
    public void deleteByOrder(String businessOrder, String orgId) throws Exception {
        if (StringUtils.isEmpty(businessOrder) || StringUtils.isEmpty(orgId)) {
            throw new Exception("参数异常");
        }
        warehouseInboundMapper.deleteByInboundOrder(businessOrder, orgId);
        warehouseInboundDetailMapper.deleteByInboundOrder(businessOrder, orgId);
    }
}
